/*
 * Copyright (C) 2011 JiangHongTiao <jjurco.sk_gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package sk.lieskove.jianghongtiao.websearch.service.ares;

import org.apache.log4j.Logger;
import sk.lieskove.jianghongtiao.aresapi.response.obj.AresOdpovedi;
import sk.lieskove.jianghongtiao.aresapi.response.obj.OdpovedFo;
import sk.lieskove.jianghongtiao.aresapi.response.obj.VypisOsoby;
import sk.lieskove.jianghongtiao.aresapi.response.obj.VypisStrankyFo;
import sk.lieskove.jianghongtiao.aresapi.websearch.AresFindPeople;
import sk.lieskove.jianghongtiao.aresapi.websearch.AresFindPeopleImpl;
import sk.lieskove.jianghongtiao.aresapi.webservice.services.*;
import sk.lieskove.jianghongtiao.common.enums.searchserviceenum.SearchServiceEnum;
import sk.lieskove.jianghongtiao.multithreaddownloader.document.RemoteDocument;
import sk.lieskove.jianghongtiao.multithreaddownloader.request.exceptions.NotEnoughParametersException;
import sk.lieskove.jianghongtiao.multithreaddownloader.request.exceptions.ParameterNotAllowedException;
import sk.lieskove.jianghongtiao.websearch.service.SearchQuery;
import sk.lieskove.jianghongtiao.websearch.service.SearchService;
import sk.lieskove.jianghongtiao.websearch.persistence.WebSearchResponse;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

/**
 * Date of create: Oct 9, 2011
 *
 * @author JiangHongTiao <jjurco.sk_gmail.com>
 * @version 2011.1009
 */
public class AresSearch implements SearchService {

    private Logger log = Logger.getLogger(AresSearch.class);
    public static final SearchServiceEnum[] SUPPORTED_SERVICES = {
        SearchServiceEnum.ARES_BASIC,
        SearchServiceEnum.ARES_CHURCHES_AND_RELIGIOUS_SOCIETIES,
        SearchServiceEnum.ARES_CIVIC_ASSOCIATIONS_GUILDS_CLUBS,
        SearchServiceEnum.ARES_COMMERCIAL_REGISTER,
        SearchServiceEnum.ARES_COMMON_AGRICULTURAL_REGISTER,
        SearchServiceEnum.ARES_ECONOMIC_ENTITIES,
        SearchServiceEnum.ARES_FOREIGN_EXCHANGE_SPOTS_AND_LICENCES,
        SearchServiceEnum.ARES_INSOLVENT_REGISTER,
        SearchServiceEnum.ARES_INSURANCE_INTERMEDIARIES_LOSS_ADJUSTERS,
        SearchServiceEnum.ARES_POLITICAL_PARTIES_MOVEMENTS,
        SearchServiceEnum.ARES_REGISTER_ECONOMIC_ENTITIES_STATISTICAL_OFFICE,
        SearchServiceEnum.ARES_REGISTER_OF_BANKRUPTS,
        SearchServiceEnum.ARES_REGISTER_OF_HEALTH,
        SearchServiceEnum.ARES_REGISTRY,
        SearchServiceEnum.ARES_SCHOOL_REGISTER,
        SearchServiceEnum.ARES_STANDARD,
        SearchServiceEnum.ARES_TRADE_REGISTER
    };

    @Override
    public List<WebSearchResponse> searchAll(SearchQuery query) {
        return search(query, Integer.MAX_VALUE, SUPPORTED_SERVICES);
    }

    @Override
    public List<WebSearchResponse> searchAll(SearchQuery query,
            int numberOfResults) {
        return search(query, numberOfResults, SUPPORTED_SERVICES);
    }

    @Override
    public List<WebSearchResponse> search(SearchQuery query,
            SearchServiceEnum[] services) {
        return search(query, Integer.MAX_VALUE, services);
    }

    @Override
    public List<WebSearchResponse> search(SearchQuery query, int numberOfResults,
            SearchServiceEnum[] services) {
        String baseQuery = query.getBaseQuery();
        
        Set<String> icoList = findByName(baseQuery);
        List<WebSearchResponse> result = new ArrayList<WebSearchResponse>();

        for (SearchServiceEnum service : services) {
            int i = 0;
            for (String ico : icoList) {
                try {
                    EmptyService s = getService(service);
                    if(s != null){
                        s.putParam("ico", ico);
                        RemoteDocument answer = s.getAnswer();
                        WebSearchResponse webSearchResponse = new WebSearchResponse();
                        webSearchResponse.setRemoteDocument(answer);
                        webSearchResponse.setUuid(answer.getUUID());
                        webSearchResponse.setServiceName(service.value());
                        webSearchResponse.setSearchPosition(i);
                        webSearchResponse.setTitle(service.value() + ": "+query.getBaseQuery());
                        webSearchResponse.setDescription("Search in: "+
                                service.value() + " for ICO "+ico+". Query was: "+
                                query.getBaseQuery());
                        webSearchResponse.setSearchQuery(baseQuery);
                        result.add(webSearchResponse);
                    }
                } catch (ParameterNotAllowedException ex) {
                    log.error("Parameter 'ico' is not allowed in this service: ",
                            ex);
                } catch (NotEnoughParametersException ex) {
                    log.error("There is not enoug parameters for this service!",
                            ex);
                }
                i++;
            }

        }
        return result;
    }

    /**
     * Search in Ares server person by name
     * 
     * @param name name of the person
     * @return set of ICO associated with person
     */
    public Set<String> findByName(String name) {
        Set<String> result = new TreeSet<String>();
        AresFindPeople findPeople = new AresFindPeopleImpl();
        AresOdpovedi persons = findPeople.findByName(name);
        return extractIco(persons);
    }

    /**
     * get all ICO from AresOdpovedi instance
     * 
     * @param odpovedi search results
     * @return set of all ICO from search results
     */
    private Set<String> extractIco(AresOdpovedi odpovedi) {
        Set<String> result = new TreeSet<String>();
        for (OdpovedFo odpovedFo : odpovedi.getOdpoved()) {
            for (VypisStrankyFo vypisStrankyFo : odpovedFo.getV()) {
                for (VypisOsoby vypisOsoby : vypisStrankyFo.getS()) {
                    result.add(vypisOsoby.getIco());
                }
            }
        }
        return result;
    }

    private EmptyService getService(SearchServiceEnum service) {
        EmptyService s = null;
        switch (service) {
            case ARES_BASIC:
                s = new BasicService();
                break;
            case ARES_CHURCHES_AND_RELIGIOUS_SOCIETIES:
                s = new ChurchesAndReligiousSocietiesService();
                break;
            case ARES_CIVIC_ASSOCIATIONS_GUILDS_CLUBS:
                s = new CivicAssociationsGuildsClubsService();
                break;
            case ARES_COMMERCIAL_REGISTER:
                s = new CommercialRegisterService();
                break;
            case ARES_COMMON_AGRICULTURAL_REGISTER:
                s = new CommonAgriculturalRegisterService();
                break;
            case ARES_ECONOMIC_ENTITIES:
                s = new EconomicEntitiesService();
                break;
            case ARES_FOREIGN_EXCHANGE_SPOTS_AND_LICENCES:
                s = new ForeignExchangeSpotsALicencesService();
                break;
            case ARES_INSOLVENT_REGISTER:
                s = new InsolventRegisterService();
                break;
            case ARES_INSURANCE_INTERMEDIARIES_LOSS_ADJUSTERS:
                s = new InsuranceIntermediariesLossAdjustersService();
                break;
            case ARES_POLITICAL_PARTIES_MOVEMENTS:
                s = new PoliticalPartiesMovementsService();
                break;
            case ARES_REGISTER_ECONOMIC_ENTITIES_STATISTICAL_OFFICE:
                s = new RegisterEconomicEntitiesStatisticalOfficeService();
                break;
            case ARES_REGISTER_OF_HEALTH:
                s = new RegisterOfHealthService();
                break;
            case ARES_REGISTRY:
                s = new RegistryService();
                break;
            case ARES_SCHOOL_REGISTER:
                s = new SchoolRegisterService();
                break;
            case ARES_STANDARD:
                s = new StandardService();
                break;
            case ARES_TRADE_REGISTER:
                s = new TradeRegisterService();
                break;
        }
        return s;
    }
}
